<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="福卡名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入福卡名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wsg:fk:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wsg:fk:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wsg:fk:remove']"
        >删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="fkList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="福卡名称" align="center" prop="name" />
      <el-table-column label="状态" align="center" :formatter="statusFormat"/>
      <el-table-column label="正面图片" align="center" prop="imgPath" >
        <template slot-scope="scope">
          <el-image :src="base_url+scope.row.imgPath" style="height: 40px;width: 40px"/>
        </template>
      </el-table-column>
      <el-table-column label="反面图片" align="center" prop="backImgPath" >
        <template slot-scope="scope">
          <el-image :src="base_url+scope.row.backImgPath" style="height: 40px;width: 40px"/>
        </template>
      </el-table-column>
      <el-table-column label="总数量" align="center" prop="totalNum" />
      <el-table-column label="已发放数量" align="center" prop="provideNum" />
      <el-table-column label="机率" align="center" prop="rate" />
      <!--<el-table-column label="文字介绍" align="center" prop="textIntroduction" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wsg:fk:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wsg:fk:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改万寿宫-福卡对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" class="form" label-width="150px">
        <el-col :span="12">
          <el-form-item label="福卡名称" prop="name" >
            <el-input v-model="form.name" placeholder="请输入福卡名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-select v-model="form.status" placeholder="状态" clearable size="small">
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="总数量" prop="totalNum">
            <el-input v-model="form.totalNum" placeholder="请输入总数量" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已发放数量" prop="provideNum" label-width="150px">
            <el-input v-model="form.provideNum" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="机率" prop="rate">
            <el-input v-model="form.rate" placeholder="请输入机率" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="文字介绍" prop="textIntroduction">
            <el-input v-model="form.textIntroduction" type="textarea" placeholder="请输入文字介绍" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="图片上传">
            <el-upload
              class="avatar-uploader"
              :action="url"
              :show-file-list="false"
              :on-success="uploadSuccess"
              :limit="1"
              :file-list="fileList"
              :headers="headers"
              :before-upload="checkUpload"
              :disabled="flag">
              <img v-if="files.path" :src="base_url+files.path" class="avatar" width="100px" height="100px">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="万寿宫介绍" label-width="150px" prop="wsgIntroduction">
            <Editor v-model="form.wsgIntroduction" style="height: 290px;"/>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFk, getFk, delFk, addFk, updateFk, exportFk, delFile} from "@/api/wsg/fk";
import Editor from '@/components/Editor';
import {getToken} from "@/utils/auth";

export default {
  name: "Fk",
  components: {
    Editor
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 万寿宫-福卡表格数据
      fkList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        wxClientId: undefined,
        name: undefined,
        status: undefined,
        imgPath: undefined,
        totalNum: undefined,
        provideNum: undefined,
        rate: undefined
      },
      fkSize: undefined,
      // 表单参数
      form: {},
      // 状态字典
      statusOptions: [],
      // 表单校验
      rules: {
        name: [
          { required: true, message: "福卡名称不能为空", trigger: "blur" }
        ],
        totalNum: [
          { required: true, message: "总数量不能为空", trigger: "blur" },
          {
            pattern: /^[1-9]\d*$/,
            message: "请输入正确的总数量",
            trigger: "blur"
          }
        ],
        rate: [
          { required: true, message: "几率不能为空", trigger: "blur"},
          {
            pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
            message: "请输入正确的几率",
            trigger: "blur"
          }
        ],
        textIntroduction: [
          { required: true, message: "文字介绍不能为空", trigger: "blur" }
        ],
        wsgIntroduction: [
          { required: true, message: "万寿宫介绍不能为空", trigger: "blur" }
        ]
      },
      base_url: process.env.VUE_APP_BASE_API,
      //文件列
      fileList: [],
      // 设置上传的请求头部
      headers: {Authorization: "Bearer " + getToken()},
      //上传地址
      url: process.env.VUE_APP_BASE_API + "/common/upload",
      //是否禁用上传
      flag: false,
      //图片路径
      files: {path: ''},
      // 表单校验
    };
  },
  created() {
    this.getDicts("wx_fk_state").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("wsg_fk_size").then(response => {
      this.fkSize = parseInt(response.data[0].dictValue);
    });
    this.getList();
  },
  watch: {
    $route(){
      this.getList();
    }
	},
  methods: {
    /** 查询万寿宫-福卡列表 */
    getList() {
      this.loading = true;
      listFk(this.queryParams).then(response => {
        this.fkList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        wxClientId: undefined,
        name: undefined,
        status: "0",
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        totalNum: undefined,
        provideNum: undefined,
        rate: undefined
      };
      this.resetForm("form");
      this.fileList = [];
      this.flag = false
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      console.log(this.fkList.length);
      console.log(this.fkSize);
      if (this.fkList.length >= this.fkSize) {
          this.msgError("只能添加" + this.fkSize + "张福卡");
          return;
      }
      /*this.reset();
      this.open = true;
      this.title = "添加万寿宫-福卡";*/
      var location = '/wsg/fk/save';
      this.$router.push({'path': location, name: 'Fk/add', 'query': {}})
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      var location = '/wsg/fk/save';
      this.$router.push({'path':location, name:'Fk/edit', 'query': {id:id}})
      /*getFk(id).then(response => {
        this.form = response.data;
        this.files.path = response.data.imgPath;
        this.open = true;
        this.title = "修改万寿宫-福卡";
      });*/
    },
    /** 提交按钮 */
    submitForm: function() {
      var imgPath = this.form.imgPath;
      console.log(imgPath);
      if (imgPath == '' || imgPath == undefined || imgPath == null) {
          this.msgError("请上传图片");
          return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateFk(this.form).then(response => {
              console.log(response);
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addFk(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除万寿宫-福卡编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delFk(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有万寿宫-福卡数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportFk(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    /**关闭dialog的按钮触发*/
    closeDialog() {
      if (this.files.path != undefined && this.files.path != '') {
        console.log("关闭dialog触发删除")
        delFile(this.files).then(response => {
          this.files.path=undefined;
          console.log(response)
      })
      }
    },
    /** 上传之前的校验 */
    checkUpload(file) {
      console.log("文件类型", file)
      const imgType = file.type
      //图片不大于2M
      const isLtSize = file.size / 1024 / 1024 < 2
      if (['image/png', 'image/jpeg', 'image/jpg', 'image/gif'].indexOf(imgType) === -1) {
        this.$message.error('上传图片只能是 JPG、PNG、GIF格式!')
        return false;
      }
      if (!isLtSize) {
        this.$message.error(`上传图片大小不能超过2MB!`)
        return false;
      }
    },
    /** 上传成功后的回调 */
    uploadSuccess(response, file, fileList) {
      console.log("1111");
      this.form.imgPath = response.fileName
      this.files.path = response.fileName
      this.flag = true
    },
  }
};
</script>
<style scoped>
  .avatar-uploader i {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader i:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .form{
    height: 600px;
  }
</style>
